import React, {useState, useEffect} from 'react'

import {Container} from './style'

import { Button, Input, Table, Space, Popconfirm, message, Modal, Form} from 'antd'

import moment from 'moment'

import FriendlylinkRequest from '../../../../request/friendlylink_request'

const friendlylink_request = new FriendlylinkRequest()

function FriendlyLinkAdmin(){
    const [isChangeSort, setIsChangeSort] = useState(false)
    const [form] = Form.useForm()
    const layout = {
        labelCol: { span: 6 },
        wrapperCol: { span: 16 },
    }
    let tableColunm = 
        [
            {
                title: '序号',
                key: 'number',
                render: (text, record, index) => {
                    return index + 1
                }
            },
            {
                title: '链接名称',
                dataIndex: 'name',
                key: 'name',
                width: 150
            },
            {
                title: '简要描述',
                dataIndex: 'desc',
                key: 'desc',
            },
            {
                title: '创建时间',
                key: 'createdate',
                width: 160,
                render: (text, record) => {
                    return moment(Number(record.createdate)).format('YYYY-MM-DD HH:mm:ss')
                }
            },
            {
                title: '链接路径',
                key: 'path',
                dataIndex: 'path',
            },
            {
                title: '显示顺序',
                key: 'sort',
                width: 100,
                render: (text, record) => (
                    <div>
                        {
                            isChangeSort ? 
                            <Input placeholder="顺序号" value={record.sort} onChange={(e) => handleSortInput(e.target.value, record.id)} style={{width: 68}}/>
                            : <span>{record.sort}</span>
                        }
                    </div>
                )
            },
            {
                title: '操作',
                key: 'action',
                render: (text, record) => (
                    <Space>
                        <Button type="primary" size="small" onClick={() => startModifyFriendlyLink(record)}>编辑</Button>
                        <Popconfirm
                            title="确定永久删除？"
                            okText="删除"
                            cancelText="暂不"
                            onConfirm={() => deleteFriendlyLink(record.id)}
                        >
                            <Button type="primary" size="small" danger>删除</Button>
                        </Popconfirm>
                    </Space>
                ),
            },
        ]
     //表格结构
    const [tableData, setTableData] = useState([]) //表格数据

    const [keyword, setKeyword] = useState('')

    const [visible, setVisible] = useState(false)

    const [currentObj, setCurrentObj] = useState('')

    const [type, setType] = useState('')

    useEffect(() => {
        getFriendlyLinkList()
    }, [])

    const startModifyFriendlyLink = (obj) => {
        setCurrentObj(obj)
        setType('edit')
        
        setTimeout(() => {
            setVisible(true)
            form.setFieldsValue({
                name: obj.name,
                desc: obj.desc,
                path: obj.path,
                id: obj.id
            })
        }, 0)
    }

    const getFriendlyLinkList = () => {
        friendlylink_request.getFriendlyLinkList({
            name: keyword,
            islogin: '1'
        }).then(res => {
            setTableData(res.map((item, index) => {
                return {
                    ...item,
                    key: index
                }
            }))
        })
    }

    const deleteFriendlyLink = (id) => {
        friendlylink_request.deleteFriendlyLink({
            id
        }).then(res => {
            message.success('删除成功！')
            getFriendlyLinkList()
        })
    }
    
    const confirmModal = () => {
        if(type === 'add'){
            friendlylink_request.addFriendlyLink({
                name: form.getFieldValue('name'),
                desc: form.getFieldValue('desc'),
                path: form.getFieldValue('path')
            }).then(res => {
                message.success('新增成功！')
                setVisible(false)
                form.resetFields()
                getFriendlyLinkList()
            })
        }else if(type === 'edit'){
            friendlylink_request.modifyFriendlyLink({
                id: currentObj.id,
                name: form.getFieldValue('name'),
                desc: form.getFieldValue('desc'),
                path: form.getFieldValue('path')
            }).then(res => {
                message.success('修改成功！')
                setVisible(false)
                form.resetFields()
                getFriendlyLinkList()
            })
        }
        
    }

    const handleSortInput = (val, id) => {
        let value = Number(val) < 1 ? 1 : Number(val) > tableData.length ? tableData.length : Number(val)
        const reg = /^-?\d*(\.\d*)?$/
        if ((!isNaN(value) && reg.test(value)) || value === '' || value === '-') {
            let list = [...tableData]
            list = list.map(item => {
                if(item.id === id){
                    return {
                        ...item,
                        sort: Number(value)
                    }
                }else{
                    return item
                }
            })
            setTableData(list)
        }
    }

    const changeSort = () => {
        if(isChangeSort){
            let sortIdList = []
            let list = tableData.sort((a, b) => {
                return a.sort - b.sort
            })
            list.forEach(item => {
                sortIdList.push(item.id)
            })
            friendlylink_request.changeFriendlyLinkSort({
                ids: JSON.stringify(sortIdList)
            }).then(res => {
                message.success('操作成功！')
                setIsChangeSort(false)
                getFriendlyLinkList()
            })
        }else{
            setIsChangeSort(true)
        }
    }

    const startAdd = () => {
        setVisible(true)
        setType('add')
    }

    const closeModal = () => {
        setVisible(false)
        form.resetFields()
    }
    return (
        <Container>
            <div className="top">
                <Space>
                    <Button type="primary" onClick={startAdd}>新增链接</Button>
                    <Input placeholder="请输入链接关键字" style={{ width: 200 }} value={keyword} allowClear onChange={(e) => setKeyword(e.target.value)} onPressEnter={getFriendlyLinkList}></Input>
                    <Button type="primary" onClick={getFriendlyLinkList}>查询链接</Button>
                    <Button type="primary" danger={isChangeSort} onClick={changeSort}>{isChangeSort ? '保存顺序' : '修改顺序'}</Button>
                </Space>
            </div>
            <div className="bottom">
                <Table columns={tableColunm} pagination={{showSizeChanger: true, showTotal: (total) => `共 ${total} 条`}} dataSource={tableData} />
            </div>
            <Modal
                title={type === 'add' ? '新增链接' : '编辑链接'}
                visible={visible}
                onOk={confirmModal}
                maskClosable={false}
                onCancel={closeModal}
            >
                <Form
                    form={form}
                    onFinish={confirmModal}
                    {...layout}
                >
                    <Form.Item
                        label="名称"
                        name="name"
                    >
                        <Input placeholder="请填写链接名称" style={{width: 220}}/>
                    </Form.Item>
                    <Form.Item
                        label="简单描述"
                        name="desc"
                    >
                        <Input.TextArea style={{width: '100%'}} placeholder="请填写链接描述" rows={4}/>
                    </Form.Item>
                    <Form.Item
                        label="路径名"
                        name="path"
                    >
                        <Input placeholder="请填写链接路径名" style={{width: 220}}/>
                    </Form.Item>
                </Form>
            </Modal>
        </Container>
    )
}

export default FriendlyLinkAdmin